<template>
  <NavBar title="粉丝" backgroundColor="#161622">
    <template #left>
      <div class="left" @click="handleClick">
        <Icon name="zuojiantou" size="18" color="#fff"></Icon>
      </div>
    </template>
  </NavBar>
  <div class="fan">
    <!-- 粉丝列表 -->
    <div class="fan_list">
      <div class="fan_item" v-for="item in fanList" :key="item.userId">
        <div class="avatar">
          <img :src="item.userAvatar" alt="">
        </div>
        <div class="info">
          <div class="name">
            {{ item.userNickname }}
          </div>
          <div class="desc">
            关注了你
          </div>
          <div class="time">
            {{ item.formattedTime }}
          </div>
        </div>
        <div class="follow" @click="handleFollow(item.userId)" :class="{ 'active': item.bothStatus <= 0 }">
          <!-- 是否关注 -->
          {{ item.bothStatus >= 1 ? '互相关注' : '关注' }}
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { onMounted, ref } from 'vue'
import { useDateFormat } from '@/composables/useDateFormat'
import NavBar from '@/components/Common/NavBar/index.vue'
import Icon from '@/components/Common/Icon/index.vue'
import { useRouter } from 'vue-router'
import { getFanListAPI, followAPI } from '@/api/message'
import { useUserIDStore } from '@/stores/UserID'

// 路由
const router = useRouter()

// 用户 ID
const userIDStore = useUserIDStore()
const userId = userIDStore.userInfo?.userId

// 粉丝列表
const fanList = ref([])

// 返回消息页
const handleClick = () => {
  router.push({ name: 'message' })
}

// 获取粉丝列表
const getFanList = async () => {
  try {
    const res = await getFanListAPI(userId)
    if (res.code === 200) {
      fanList.value = res.data.map(item => ({
        ...item,
        userAvatar: 'http://43.138.15.137:3000' + item.userAvatar,
        formattedTime: useDateFormat(item.createdAt, 'YYYY-MM-DD', { relative: true }).formatted
      }))
    }
  } catch (error) {
    console.error('获取粉丝列表失败:', error)
  }
}

// 关注 / 取消关注
const handleFollow = async (followUserId) => {
  // 找到对应的粉丝项
  const item = fanList.value.find(u => u.userId === followUserId)
  if (!item) return

  // 保存原始状态，用于失败时回滚
  const originalBothStatus = item.bothStatus

  // 乐观更新：立即切换 UI 状态
  if (item.bothStatus <= 0) {
    // 当前未关注 → 点击后变为“互相关注”（简化为 1）
    item.bothStatus = 1
  } else {
    // 当前已关注（互相关注）→ 点击后变为未关注（设为 0）
    item.bothStatus = 0
  }

  try {
    // 发送请求
    const res = await followAPI(userId, followUserId)

    if (res.code !== 200) {
      // 请求失败：回滚状态
      item.bothStatus = originalBothStatus
      console.error('操作失败:', res.msg || '未知错误')
    }
    // 成功则保留新状态，无需操作
  } catch (error) {
    // 网络或异常错误：回滚
    item.bothStatus = originalBothStatus
    console.error('网络请求失败:', error)
  }
}

// 挂载时获取数据
onMounted(() => {
  getFanList()
})
</script>

<style lang="scss" scoped>
.fan {
  background-color: #161622;
  padding-bottom: 35px;

  .fan_list {
    padding: 10px;

    .fan_item {
      display: flex;
      align-items: center;
      margin-bottom: 10px;

      .avatar {
        width: 45px;
        height: 45px;
        border-radius: 50%;
        margin-right: 10px;

        img {
          width: 100%;
          height: 100%;
          border-radius: 50%;
        }
      }

      .info {
        flex: 1;


        .name {
          font-size: 14px;
          font-weight: bold;
          line-height: 1;
          color: #fff;
        }

        .desc {
          font-size: 14px;
          color: #fff;
          margin-bottom: 5px;
          font-weight: bold;
        }

        .time {
          font-size: 12px;
          font-weight: bold;
          color: #879394;
        }
      }

      .follow {
        width: 60px;
        height: 24px;
        display: flex;
        align-items: center;
        justify-content: center;
        font-size: 12px;
        font-weight: bold;
        color: #fff;
        padding: 4px 8px;
        border-radius: 2px;
        background-color: #393b44;
        white-space: nowrap;

        &.active {
          background-color: #f9355f;
        }
      }
    }
  }

}
</style>